#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <string.h>
#include "mysql.h"

MYSQL *mysql;
MYSQL_RES *results;
MYSQL_ROW record;

static char *server_options[] = { "mysql_test", "--defaults-file=my.cnf" };
int num_elements = sizeof(server_options)/ sizeof(char *);
static char *server_groups[] = { "libmysqld_server", "libmysqld_client" };


int connectdb(void)
{


	char *filename = "./config.conf";
	printf("begin work!");

	loadFileConfigure(filename);
	char *mysql_connect = getFileConfigVal("mysql_connect");
	char *port = getFileConfigVal("port");
	char *user = getFileConfigVal("user");
	char *passwd = getFileConfigVal("passwd");
	char *dbname = getFileConfigVal("dbname");
	char *mysock = getFileConfigVal("mysock");

	mysql = mysql_init(NULL);

	if (!mysql_real_connect(mysql, mysql_connect, user, passwd, dbname, 0, mysock, 0))
	{      fprintf(stderr, "无法连接数据库，错误原因：%s\n",
		      mysql_error(mysql));
		return 0;
    }

   return 1;
}

void closedb() {

	   mysql_close(mysql);
	   mysql_server_end();
}

MYSQL_RES * executeQuery(char *query) {

         //下面执行的语句为连接设置字符集
	   mysql_real_query(mysql,"SET NAMES 'utf8'",(unsigned int) strlen("SET NAMES 'utf8'"));			// 执行查询语句

	   int t = mysql_real_query(mysql,query,(unsigned int) strlen(query));			// 执行查询语句

	   if (t) {

	         printf("查询数据库失败：%s\n", mysql_error(mysql));
	         return NULL;
	   }
	   else {
		   results = mysql_store_result(mysql);

		   return results;
//		   while((record = mysql_fetch_row(results)))
//		   {
//			// 在结果集内步进
//			   int t;
//					for(t = 0; t < (int)mysql_num_fields(results); t++)
//							  printf("%s ",record[t]);										// 输出每列的数据
//					printf("\n");
//		   }
//		   mysql_free_result(results);
	   }

}

int executeUpdate(char *query) {

         //下面执行的语句为连接设置字符集
	   connectdb();
	   mysql_real_query(mysql,"SET NAMES 'utf8'",(unsigned int) strlen("SET NAMES 'utf8'"));			// 执行查询语句

	   int t = mysql_real_query(mysql,query,(unsigned int) strlen(query));			// 执行查询语句

	   return t;
}

//int main(void) {
//
//
//	char *filename = "/root/install.log";
//	char *md5 = malloc(33 *sizeof(char));
//	CalcFileMD5(filename, md5);
//	printf("the x4.mkv MD5 is %s", md5);
//	connectdb();
//
//	char psql[1024];
//	memset(psql, 0, sizeof(psql));
//	sprintf(psql, "insert into v_baseinfo(vid) values('%s')", md5 );
//	int results =  executeUpdate(psql);
//	closedb();
//}
